﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

namespace Jayden.Dll.Core.Logging
{
	public class FileHandler : Handler
	{
		private string m_Filepath;
		private Queue<LogRecord> m_Records = new Queue<LogRecord>();
		private Thread m_WriterThread;

		public FileHandler(string filepath)
		{
			m_Filepath = filepath;

			using (StreamWriter writer = File.AppendText(m_Filepath))
				writer.WriteLine(string.Empty.PadRight(80, '='));
		}

		public override void Close()
		{
			if (m_WriterThread != null)
			{
				Thread thread = m_WriterThread;
				m_WriterThread = null;
				thread.Join();
			}
		}

		public override void Flush() { WriteRecords(); }

		private void Run()
		{
			Thread.Sleep(10000);
			WriteRecords();
			m_WriterThread = null;
		}

		private void WriteRecords()
		{
			if (string.IsNullOrWhiteSpace(m_Filepath))
				return;
			List<LogRecord> list = null;
			lock (m_Records)
			{
				list = new List<LogRecord>(m_Records);
				m_Records.Clear();
			}
			StringBuilder builder = new StringBuilder();
			foreach (LogRecord record in list)
			{
				string messageFormatted = Formatter.FormatMessage(record);
				builder.Append(messageFormatted);
			}
			if (builder.Length > 0)
			{
				lock (this)
				{
					using (StreamWriter writer = File.AppendText(m_Filepath))
						writer.Write(builder.ToString());
				}
			}
		}

		public override void Publish(LogRecord record)
		{
			lock (m_Records)
			{
				m_Records.Enqueue(record);

				if (m_WriterThread == null)
				{
					m_WriterThread = new Thread(Run);
					m_WriterThread.Start();
				}
			}
		}
	}
}
